/**
 * 
 */
package pt.mleiria.sound;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

/**
 * @author NB13712
 * 
 */
public class Alarm extends TimerTask {
	private static final Logger LOG = Logger.getLogger(Alarm.class);
	private final String hhmm;
	private SoundBehaviour soundBehaviour;

	public Alarm(final String hhmm, final SoundBehaviour soundBehaviour) {
		this.hhmm = hhmm;
		this.soundBehaviour = soundBehaviour;
		scheduleAlarm();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.TimerTask#run()
	 */
	@Override
	public void run() {
		LOG.info("running task");
		soundBehaviour.makeSound();

	}

	private void scheduleAlarm() {
		final Timer timer = new Timer();
		final Calendar date = Calendar.getInstance();
		int hour = Integer.parseInt(hhmm.substring(0, 2));
		final int minute = Integer.parseInt(hhmm.substring(3, 5));
		if (hour > 12) {
			hour = hour - 12;
			date.set(Calendar.AM_PM, Calendar.PM);
		} else {
			date.set(Calendar.AM_PM, Calendar.AM);
		}
		date.set(Calendar.HOUR, hour);
		date.set(Calendar.MINUTE, minute);
		date.set(Calendar.SECOND, 0);
		date.set(Calendar.MILLISECOND, 0);
		// timer.schedule(new Alarm(), date.getTime(), 1000 * 60 * 60 * 24);
		final String log = "Starting alarm scheduler for [" + hour + ":" + minute + "]:" + date.getTime(); 
		LOG.info(log);
		new TextToSpeech(log).makeSound();
		timer.schedule(this, date.getTime(), 1000 * 60);
	}

}
